<template>
  <view>
    <!-- 普通选择 -->
    <u-picker
      v-if="!date"
      close-on-click-overlay
      @close="close"
      @confirm="confirm"
      @cancel="close"
      :show="show"
      :columns="dataList"
      :key-name="keyName"
      v-bind="$attrs"
    />
    <!-- 日期选择 -->
    <u-datetime-picker
      v-else
      close-on-click-overlay
      @close="close"
      @cancel="close"
      @confirm="confirm"
      :show="show"
      v-model="dateData"
      :mode="dateMode"
      v-bind="$attrs"
    />
  </view>
</template>
<script setup>
import dayjs from 'dayjs'
import { computed, ref, useAttrs } from 'vue'

const $attrs = useAttrs()

const props = defineProps({
  // 使用日期选择器
  date: {
    type: Boolean,
    default: false
  },
  dateMode: {
    type: String,
    default: 'date' // 日期模式有完整时间：datetime，年月日：date,时分：time，月份：year-month
  },
  // 绑定的值
  modelValue: {
    type: String,
    default: ''
  },
  show: {
    type: Boolean,
    default: false
  },
  // 数组列表
  list: {
    type: Array,
    default: () => ([])
  },
  // 数组绑定的key值，即需要显示的值
  keyName: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'confirm', 'close'])

const dataList = computed(() => {
  const List = []
  List.push(props.list)
  return List
})
const dateData = ref(dayjs().valueOf())
const confirm = (e) => {
  // 当模式为日期选择器时
  if (props.date) {
    let formatTime = ''
    if (props.dateMode === 'datetime') {
      formatTime = dayjs(e.value).format('YYYY-MM-DD HH:mm:ss')
      emit('update:modelValue', formatTime)
    } else if (props.dateMode === 'date') {
      formatTime = dayjs(e.value).format('YYYY-MM-DD')
      emit('update:modelValue', formatTime)
    }
    emit('confirm', formatTime)
  } else {
    emit('update:modelValue', e.value[0][props.keyName])
    emit('confirm', e.value[0])
  }
  emit('close')
}
const close = () => {
  emit('close')
}
</script>
<style lang="scss" scoped></style>
